const Koa = require('koa')
const app = new Koa()
const views = require('koa-views') //模板渲染
const json = require('koa-json') //json打印
const onerror = require('koa-onerror') //错误处理
const bodyparser = require('koa-bodyparser') //请求体JSON解析
const convert = require('koa-convert') //转换
const logger = require('koa-logger') //
const cors = require('koa-cors') //跨域
const resource = require('koa-static') //静态资源托管

const routes = require('./routes/index')
const temp = require('./routes/temp')

//log工具
const logUtil = require('./utils/log_util');

// error handler
onerror(app)

app.use(convert(cors()))
// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  //响应开始时间
  const start = new Date();
  //响应间隔时间
  var ms;
  try {
    //开始进入到下一个中间件
    await next();

    ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);

    //记录响应日志
    logUtil.logResponse(ctx, ms);

  } catch (error) {

    ms = new Date() - start;
    //记录异常日志
    logUtil.logError(ctx, error, ms);
  }
});

// 临时
app.use(temp.routes(), temp.allowedMethods())
// routes
app.use(routes.routes(), routes.allowedMethods())

module.exports = app
